package com.caifu.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.caifu.bean.Result;
import com.caifu.bean.ResultUtil;
import com.caifu.pojo.SysLog;
import com.caifu.pojo.SysUser;
import com.caifu.service.SysLogService;
import com.caifu.service.SysUserService;
import com.caifu.util.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Map;

/**
 * @Auther: Lyf
 * @Date: 2020/7/14 16:02
 * @Description: 用户管理控制层
 */
@Controller
@RequestMapping("user")
public class UserController extends AbstractController {

    final static Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private SysUserService userService;

    @Autowired
    private SysLogService logService;


    /**
     * 修改密码
     */
    @PostMapping("updatePwd")
    @ResponseBody
    public Result updatePwd(String pwd) {
        SysUser user = getUser();
        try {
            return userService.updatePwd(user, pwd);
        } catch (Exception e) {
            String msg = "网络异常";
            if (Utils.isNotNull(e.getMessage())) {
                msg = e.getMessage();
            }
            logger.error(e.toString());
            e.printStackTrace();
            return error(500, msg);
        }
    }


    /**
     * 进入操作员管理
     * 192.168.1.180:9999/caifu/user/index
     * 2020年8月9日
     * codeBy szt
     */
    @RequestMapping("/index")
    @RequiresPermissions("yonghuguanli")
    public String index(String initPage, ModelMap map) {
        try {
            map.put("initPage", initPage);
        } catch (Exception e) {
            logger.error(e.toString());
        }
        return "view/user/index";
    }

    @RequestMapping("/userMenu")
    @RequiresPermissions("yonghuguanli")
    public String userMenu(ModelMap map, String userNo, String userPage) {
        map.put("userNo", userNo);
        map.put("userPage", userPage);
        return "view/user/userMenu";
    }

    /**
     * 获取操作员列表
     * 2020年8月11日
     * codeBy szt
     */
    @RequestMapping("/getUserList")
    @ResponseBody
    @RequiresPermissions("yonghuguanli")
    public Result getUserList(int currentPage, int pageSize, String loginName, String userName, String phone, String userType) {
        try {
            //获取操作员信息列表
            if (StringUtils.isNotBlank(phone)) {
                phone = AesMyUtil.Encrypt(phone);
            }
            IPage<Map<String, Object>> userPage = userService.getUserList(currentPage, pageSize, loginName, userName, phone, userType);
            for (Map<String, Object> tmp : userPage.getRecords()) {
                String tmpPhone = (String) tmp.get("PHONE");
                Integer userNo = (Integer) tmp.get("USER_NO");
                tmp.put("PHONE", AesMyUtil.Decrypt(tmpPhone));
                tmp.put("USER_NO", DesUtil.encrypt(userNo + ""));
            }
            return ResultUtil.success("data", userPage);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("获取用户列表失败！");
            return ResultUtil.error(199, "获取用户列表失败！");
        }
    }

    /**
     * 新增修改操作员
     * 2020年8月11日
     * codeBy szt
     */
    @RequestMapping("/save")
    @ResponseBody
    @RequiresPermissions("yonghuguanli")
    public Result save(String userNo, String userName, String loginName, String post, String phone, String orgId, String regions, String userType) {
        SysUser operUser = null;
        try {
            boolean isNew = true;
            int loginNameCount;
            userNo = DesUtil.decrypt(userNo);
            SysUser user = null;
            operUser = userService.getById(getUserNo());
            if (StringUtils.isNotBlank(userNo)) {
                isNew = false;
                //修改操作员信息
                loginNameCount = userService.getCountByLoginName(loginName, userNo);
                if (loginNameCount > 0) {
                    //日志记录  sys 组织架构模块  sys-201 操作员修改
                    SysLog log = new SysLog(getUserNo(), "1", "sys", "sys-201", "9", "用户账号已存在, " + operUser.getUserId() + "修改操作员失败！", Constance.currentDateTime());
                    logService.save(log);
                    return ResultUtil.error(198, "用户账号已存在，修改失败！");
                }

                int phoneExistCount = userService.count(new QueryWrapper<SysUser>().eq("phone", AesMyUtil.Encrypt(phone)).ne("user_no", userNo).ne("status", "9"));
                if (phoneExistCount > 0) {
                    //日志记录  sys 组织架构模块  sys-201 操作员修改
                    SysLog log = new SysLog(getUserNo(), "1", "sys", "sys-201", "9", "手机号已存在, " + operUser.getUserId() + "修改操作员失败！", Constance.currentDateTime());
                    logService.save(log);
                    return ResultUtil.error(199, "手机号已存在，修改失败！");
                }

                user = userService.getById(userNo);

                user.setUserId(loginName);
                user.setUserType(userType);

            } else {
                int phoneExistCount = userService.count(new QueryWrapper<SysUser>().eq("phone", AesMyUtil.Encrypt(phone)).ne("status", "9"));
                if (phoneExistCount > 0) {
                    //日志记录  sys 组织架构模块  sys-200 操作员添加
                    SysLog log = new SysLog(getUserNo(), "1", "sys", "sys-200", "9", "手机号已存在, " + operUser.getUserId() + "新增操作员失败！", Constance.currentDateTime());
                    logService.save(log);
                    return ResultUtil.error(199, "手机号已存在，保存失败！");
                }

                //新增操作员信息
                loginNameCount = userService.getCountByLoginName(loginName, null);
                if (loginNameCount <= 0) {
                    user = new SysUser();
                    user.setUserId(loginName);
                    user.setPaw("123456");


                    String salt = Util.getStringRandom(20);
                    String password = ShiroUtil.sha256("111111", salt);
                    user.setSalt(salt);
                    user.setUserPwd(password);
                    user.setCreateBy(getUser().getId() + "");
                    user.setStatus("1");
                } else {
                    //日志记录  sys 组织架构模块  sys-200 操作员添加
                    SysLog log = new SysLog(getUserNo(), "1", "sys", "sys-200", "9", "用户账号已存在, " + operUser.getUserId() + "新增操作员失败！", Constance.currentDateTime());
                    logService.save(log);
                    return ResultUtil.error(198, "用户账号已存在,保存失败！");
                }
            }

            userService.saveOrUpdate(operUser, user, isNew, regions);
            if (StringUtils.isNotBlank(userNo)) {
                return ResultUtil.success(200, "用户信息修改成功！");
            } else {
                return ResultUtil.success(200, "用户信息保存成功！");
            }


        } catch (Exception e) {
            e.printStackTrace();
            logger.error("用户信息保存失败！");
            return ResultUtil.error(199, "用户信息保存失败！");
        }
    }

    /**
     * 通过操作员编号获取用户信息
     * 2020年8月12日
     * codeBy szt
     */
    @RequestMapping("/getUserById")
    @ResponseBody
    @RequiresPermissions("yonghuguanli")
    public Result getUserById(String userNo) {
        try {
            //根据操作员编号获取用户信息
            Map<String, Object> userMap = userService.getMap(new QueryWrapper<SysUser>().eq("user_no", DesUtil.decrypt(userNo)));
            String postType = String.valueOf(userMap.get("POST_TYPE"));
            String phone = (String) userMap.get("PHONE");

            userMap.put("PHONE", AesMyUtil.Decrypt(phone));
            userMap.put("USER_NO", userNo);
            return ResultUtil.success(200, "获取用户信息成功！", userMap);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("获取用户信息失败！");
            return ResultUtil.error(199, "获取用户信息失败！");
        }
    }

    @RequestMapping("/setUserMenu")
    @ResponseBody
    @RequiresPermissions("yonghuguanli")
    public Result setUserMenu(int userNo, String menus) {
        try {
            //菜单权限配置
            userService.setUserMenu(userNo, menus);
            return ResultUtil.success(200, "菜单权限配置成功！");
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("菜单权限配置失败！");
            return ResultUtil.error(199, "菜单权限配置失败！");
        }
    }

    @RequestMapping("/resetPassword")
    @ResponseBody
    @RequiresPermissions("yonghuguanli")
    public Result resetPassword(String userNo) {
        try {
            //重置密码
            String salt = Util.getStringRandom(20);
            String password = ShiroUtil.sha256("111111", salt);
            return ResultUtil.success(200, "密码重置成功！", userService.update(new UpdateWrapper<SysUser>().lambda().set(SysUser::getPaw, "111111").set(SysUser::getSalt, salt).set(SysUser::getUserPwd, password).eq(SysUser::getId, userNo)));
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("密码重置失败！");
            return ResultUtil.error(199, "密码重置失败！");
        }
    }

    @RequestMapping("/changePassword")
    @ResponseBody
    public Result changePassword(String newPassword) {
        SysUser user = new SysUser();
        try {
            //重置密码
            int userNo = getUserNo();
            user = userService.getOne(new QueryWrapper<SysUser>().eq("user_no", getUserNo()));


            String salt = Util.getStringRandom(20);
            String password = ShiroUtil.sha256(newPassword, salt);

            user.setPaw(newPassword);
            user.setUserPwd(password);
            userService.updateById(user);
            //日志记录  sys 组织架构模块  sys-302 修改密码
            SysLog log = new SysLog(getUserNo(), "1", "sys", "sys-302", "1", user.getUserId() + "修改用户密码成功！", Constance.currentDateTime());
            logService.save(log);
            return ResultUtil.success(200, "密码修改成功！", userService.update(new UpdateWrapper<SysUser>().lambda().set(SysUser::getPaw, newPassword).set(SysUser::getSalt, salt).set(SysUser::getUserPwd, password).eq(SysUser::getId, userNo)));
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("密码修改失败！");
            //日志记录  sys 组织架构模块  sys-302 修改密码
            SysLog log = new SysLog(getUserNo(), "1", "sys", "sys-302", "9", user.getUserId() + "修改用户密码失败！", Constance.currentDateTime());
            logService.save(log);
            return ResultUtil.error(199, "密码修改失败！");
        }
    }

    /**
     * 删除操作员
     * 2020年8月11日
     * codeBy szt
     */
    @RequestMapping("/delete")
    @ResponseBody
    @RequiresPermissions("yonghuguanli")
    public Result delete(String userNo, String postType) {
        SysUser oldUser = new SysUser();
        try {
            userNo = DesUtil.decrypt(userNo);
            oldUser = userService.getById(getUserNo());
            //日志记录  sys 组织架构模块  sys-202 操作员删除
            SysLog log = new SysLog(getUserNo(), "1", "sys", "sys-202", "1", oldUser.getUserId() + "删除操作员成功[userNo=" + userNo + "]！", Constance.currentDateTime());
            logService.save(log);
            return ResultUtil.success(200, "删除用户成功！");
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("删除用户失败！");
            //日志记录  sys 组织架构模块  sys-202 操作员删除
            SysLog log = new SysLog(getUserNo(), "1", "sys", "sys-202", "9", oldUser.getUserId() + "删除操作员失败[userNo=" + userNo + "]！", Constance.currentDateTime());
            logService.save(log);
            return ResultUtil.error(199, "删除用户失败！");
        }
    }

    /**
     * 开通操作员
     * 2020年8月11日
     * codeBy szt
     */
    @RequestMapping("/open")
    @ResponseBody
    @RequiresPermissions("yonghuguanli")
    public Result open(String userNo) {
        SysUser oldUser = new SysUser();
        try {
            userNo = DesUtil.decrypt(userNo);
            oldUser = userService.getById(getUserNo());
            //日志记录  sys 组织架构模块  sys-207 操作员开通
            SysLog log = new SysLog(getUserNo(), "1", "sys", "sys-207", "1", oldUser.getUserId() + "开通操作员成功[userNo=" + userNo + "]！", Constance.currentDateTime());
            logService.save(log);
            //逻辑开通
            return ResultUtil.success(200, "开通用户成功！", userService.update(new UpdateWrapper<SysUser>().lambda().set(SysUser::getStatus, "1").eq(SysUser::getId, userNo)));
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("开通用户失败！");
            //日志记录  sys 组织架构模块  sys-207 操作员开通
            SysLog log = new SysLog(getUserNo(), "1", "sys", "sys-207", "9", oldUser.getUserId() + "开通操作员失败[userNo=" + userNo + "]！", Constance.currentDateTime());
            logService.save(log);
            return ResultUtil.error(199, "开通用户失败！");
        }
    }

    /**
     * 关闭操作员
     * 2020年8月11日
     * codeBy szt
     */
    @RequestMapping("/close")
    @ResponseBody
    @RequiresPermissions("yonghuguanli")
    public Result close(String userNo, String postType) {
        SysUser oldUser = new SysUser();
        try {
            userNo = DesUtil.decrypt(userNo);
            oldUser = userService.getById(getUserNo());
            //逻辑关闭
            //日志记录  sys 组织架构模块  sys-208 操作员关闭
            SysLog log = new SysLog(getUserNo(), "1", "sys", "sys-208", "1", oldUser.getUserId() + "关闭操作员成功[userNo=" + userNo + "]！", Constance.currentDateTime());
            logService.save(log);
            return ResultUtil.success(200, "停用用户成功！");
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("关闭用户失败！");
            //日志记录  sys 组织架构模块  sys-208 操作员关闭
            SysLog log = new SysLog(getUserNo(), "1", "sys", "sys-208", "9", oldUser.getUserId() + "关闭操作员成功[userNo=" + userNo + "]！", Constance.currentDateTime());
            logService.save(log);
            return ResultUtil.error(199, "停用用户失败！");
        }
    }

    /**
     * 设置用户应用权限
     * 2020年8月12日
     * codeBy szt
     */
    @RequestMapping("/setUserApp")
    @ResponseBody
    @RequiresPermissions("yonghuguanli")
    public Result setUserApp(String userNo, String appStr) {
        try {
            Result slt = userService.setUserApp(Integer.parseInt(DesUtil.decrypt(userNo)), appStr, getUserNo());
            logService.save((SysLog) slt.getData());
            return slt;
        } catch (Exception e) {
            logger.error("开通用户应用失败！");
            return ResultUtil.error(199, "开通用户应用失败！");
        }
    }

    /**
     * 设置用户数据权限
     * 2020年8月12日
     * codeBy szt
     */
    @RequestMapping("/setUserAuth")
    @ResponseBody
    @RequiresPermissions("yonghuguanli")
    public Result setUserAuth(String userNo, String orgStr) {
        try {
            Result slt = userService.setUserAuth(Integer.parseInt(DesUtil.decrypt(userNo)), orgStr, getUserNo());
            logService.save((SysLog) slt.getData());
            return slt;
        } catch (Exception e) {
            logger.error("设置用户权限失败！");
            return ResultUtil.error(199, "设置用户权限失败！");
        }
    }

}
